from django.db.models import *
from django.core.files.images import ImageFile
from os import path
import re, tempfile
from warnings import warn
try: 
    import yapgvb
except:
    pass


class Sentence(Model):
    """\
    This is the base class : represents a sentence.
    """
    nb = CharField(max_length=10)
    xml =  XMLField(schema_path=path.join(settings.ROOT, "core", "Paris7treebank.rng"))
    file = ForeignKey('XMLFile')
    
    tree = ForeignKey('TreeNode')
    tree_image = ImageField(upload_to="trees", blank=True)
    
    def image(self):
        if not self.tree_image:
            try:
                from ftbexplorer.core.graphs import TreeNode2Digraph
                tempname = tempfile.mktemp(".png", "tree_", path.join(settings.ROOT, "static/tmp"))
                print "Generating image to %s" % tempname
                g = TreeNode2Digraph(self.tree)
                if g.layout(yapgvb.engines.dot) != 0:
                    raise Exception, "Layout problem"
                if g.render(tempname) != 0:
                    raise Exception, "Render Problem"
                image_file = ImageFile(open(tempname, 'r'))
                self.tree_image.save(image_file.name, image_file)
                self.save()
                os.remove(tempname)
            except ImportError:
                warn("Can't import graph library", ImportWarning)
                return None
        return self.tree_image
    
    def __unicode__(self):
        """\
        return the file and index as description
        """
        return u"Sentence %s of file %s" % (self.nb, self.file.name)
    
    @permalink
    def get_absolute_url(self):
        return ('ftbexplorer.core.views.sentence', (), {
                'filename':self.file.name,
                'nb':self.nb})
    
    def words(self):
        return self.tree.words()
    
    def text(self):
        if hasattr(self, '_text'):
            return self._text
        else:
            words = self.words()
            words = map(lambda x: x.form, words)
            self._text = u" ".join(words)
            self._text = re.sub(r'([-\'\(])\s+', r'\1', self._text)
            self._text = re.sub(r'\s+([-.,\'\)])', r'\1', self._text)
            return self._text
    
    class Meta:
        app_label = 'core'
    

# class Word(Model):
#     index = IntegerField()
#     sentence = ForeignKey('Sentence')
#     form = CharField(max_length=1024)
#     lemma = CharField(max_length=1024)
#     cat = CharField(max_length=128)
#     ee = CharField(max_length=128)
#     ei = CharField(max_length=128)
#     mph = CharField(max_length=128)
#     subcat = CharField(max_length=128)
#     
# 
#     
#     def __unicode__(self):
#         return self.form
#     
#     class Meta:
#         app_label = 'core'
